package jp.co.technotree.common.controll;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;



public class ApplicationContext {
	private static String CLASSNAME=ApplicationContext.class.getName();
	private static ApplicationContext instance = null;
	private static ThreadLocal thlocal = new ThreadLocal();
	private String pathName = null;
	private Properties prop = new Properties();
	public ServletContext application;
	
	private ApplicationContext(String pathName){
//		this.pathName = pathName;
		FileInputStream fileInputStream = null;
		
		try {
			File file = new File(pathName,"/WEB-INF/config.properties");
//			File file = new File(application.getRealPath("/WEB-INF/config.properties"));
			String fileName = null;
			
			if ( file.isFile() ){
				fileName = file.getAbsolutePath();
			}
			fileInputStream = new FileInputStream(fileName);
			prop.load(fileInputStream);
			fileInputStream.close();
			fileInputStream = null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void init(String pathName){
		instance = new ApplicationContext(pathName);

	}
	
	public static ApplicationContext getInstance(){
		return instance;
	}
		
	public String getAbsoluteResourcePath(String resourceName){
		String METHODNAME = "getResource";
		//DBGLog.fwdebug(CLASSNAME,METHODNAME,"START");
		
		File file = new File(this.pathName,resourceName);
		String fileName = null;
		
		if ( file.isFile() ){
			fileName = file.getAbsolutePath();
		}
		
		//DBGLog.fwdebug(CLASSNAME,METHODNAME,"fileName:"+fileName);
		//DBGLog.fwdebug(CLASSNAME,METHODNAME,"END");
		return fileName;
		
	}

	public String getAbsolutePath(String pathName){
		String METHODNAME = "getResource";
		//DBGLog.fwdebug(CLASSNAME,METHODNAME,"START");
		
		File file = new File(this.pathName,pathName);
		String fileName = null;
		
		fileName = file.getAbsolutePath();
		
		//DBGLog.fwdebug(CLASSNAME,METHODNAME,"fileName:"+fileName);
		//DBGLog.fwdebug(CLASSNAME,METHODNAME,"END");
		return fileName;
	}
	
	public String getConfig(String key){
		return prop.getProperty(key);
	}
	
	/**
	 * スレッド毎にRequestContextを保存する。
	 * @param requestContext
	 */
	public static void setRequestContext(RequestContext requestContext){
		thlocal.set(requestContext);
	}
	
	/**
	 * スレッド毎に保存したRequestContextを取得する。
	 * @return RequestContext
	 */
	public static RequestContext getRequestContext(){
		return (RequestContext)thlocal.get();
	}
	
}
